<?php

namespace extensions\oss;

use OSS\Core\OssException;
use OSS\OssClient;
use Yii;
use yii\base\Component;


class Aliyun extends Component
{
   public $accessKeyId;
   public $accessKeySecret;
   public $endPoint;
   public $bucket;
   public $ossClient;


   public function init()
   {
       $this->ossClient=new OssClient($this->accessKeyId,$this->accessKeySecret,$this->endPoint);
   }

  /* public function __construct()
   {
       echo 'construct';
   }*/

    public function getBucket()
   {
       echo $this->bucket;
   }

    /**
     * 使用阿里云oss上传文件
     * @param $object   保存到阿里云oss的文件名
     * @param $filepath 文件在本地的绝对路径
     * @return bool     上传是否成功
     */
    public function upload($object, $filepath)
    {
        $flag = false;
        $url='';
        $error='';
        try{
            $getOssInfo=$this->oss->uploadFile($this->bucket, $object, $filepath);
            $result['url'] = $getOssInfo['info']['url'];
            $flag=true;
            if($getOssInfo['info']['url']){
                @unlink(substr($filepath, 1));
            }
        }catch(OssException $e){
            $error=$e->getMessage();
        };
        return ['status'=>$flag,'url'=>$url,'error'=>$error];
    }


    /**
     * 删除指定文件
     * @param $object 被删除的文件名
     * @return bool   删除是否成功
     */
    public function delete($object)
    {
        $res = false;
        $bucket = $this->bucket;                               //获取阿里云oss的bucket
        if ($this->oss->deleteObject($bucket, $object)){       //调用deleteObject方法把服务器文件上传到阿里云oss
            $res = true;
        }

        return $res;
    }



}


?>